//
//  Invite.swift
//  LeGou
//
//  Created by lxm on 2022/8/6.
//

import UIKit

class Invite: ZMViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    //MARK: --------------------属性--------------------
    
    let titles = ["平台赋能 1"]
    
    var loading = XMLoadingView()
    
    var images = [String]()
    // 当前选中的哪个类型
    var typeIndex = 0 {
        didSet {
            buttons.forEach { b in
                b.backgroundColor = .white
                b.setTitleColor(UIColor.zm.color333333(), for: .normal)
            }
            
            if let button = buttons.first(where: { b in
                return b.tag == typeIndex
            }) {
               button.backgroundColor = Style.mainColor
               button.setTitleColor( .white, for: .normal)
           }
        }
    }
    
    let collectionHeight : CGFloat = SCREEN_H > 736 ? 504 : 400
    
    //MARK: --------------------UI控件--------------------
    var buttons = [UIButton]()

    let topScrollView = UIScrollView().then({$0.showsHorizontalScrollIndicator = false})
    
    let topButtonStack = ZMUtil.stackView(axis: .horizontal, spacing: 8).then({$0.alignment = .center})
    // 底部view
    let bottomView = ShareBottomVIew()
    
    var collectionView : UICollectionView!
    
    let bottomLable = ZMUtil.label(title: "海报二维码和邀请链接均有锁粉效果好友注册过程自动填写邀请码", color: UIColor.zm.color333333(), font: UIFont.systemFont(ofSize: 12))
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        title = "邀请好友"
        view.addSubview(topScrollView)
        view.backgroundColor = "#F5F5F5".zm.hex()
        // top buttons
        var i = 0
        for t in titles {
//            let button = ZMUtil.button(title: t, font: UIFont.systemFont(ofSize: 12, weight: .medium), color: UIColor.zm.color333333())
//            button.contentEdgeInsets = UIEdgeInsets(top: 4, left: 10, bottom: 4, right: 10)
//            button.sizeToFit()
//            button.layer.cornerRadius = button.zm.height / 2
//            button.backgroundColor = .white
//            topButtonStack.addArrangedSubview(button)
//            button.tag = i
//            button.rx.tap.subscribe(onNext:{ [unowned self, weak button] resp in
//                self.typeIndex = button?.tag ?? 0
//
//            }).disposed(by: disposeBag)
//            i += 1
//
//            buttons.append(button)
        }
        topScrollView.addSubview(topButtonStack)
        
        
        // bottom View
        view.addSubview(bottomView)
        
        // collectionView
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 12
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_W, height: 100), collectionViewLayout: layout)
        view.addSubview(collectionView)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib.init(nibName: "InviteCell", bundle: nil), forCellWithReuseIdentifier: "InviteCell")
        collectionView.backgroundColor = .clear
        collectionView.decelerationRate = UIScrollView.DecelerationRate(rawValue: 0)
        collectionView.showsHorizontalScrollIndicator = false
        
        // bottomLable
        view.addSubview(bottomLable)
        bottomLable.textAlignment = .center
        bottomLable.numberOfLines = 2
        bottomLable.attributedText = "海报二维码"
            .zm.append(str: "和", attri: ["c" : "#999999"])
            .zm.append(str: "邀请链接", attri: ["c" : "#333333"])
            .zm.append(str: "均有", attri: ["c" : "#999999"])
            .zm.append(str: "锁粉效果", attri: ["c" : "#333333"])
            .zm.append(str: "好友注册过程", attri: ["c" : "#999999"])
            .zm.append(str: "自动填写邀请码", attri: ["c" : "#333333"])
        
        getPosters()
    }
    
    func addConstraints() {
        topScrollView.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
            make.height.equalTo(rpx(49))
        }
        
        topButtonStack.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
            make.centerY.equalToSuperview()
        }
        
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
        }
        
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(topScrollView.snp.bottom)
//            make.top.equalTo(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(rpx(collectionHeight))
        }
        
        bottomLable.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom).offset(rpx(17))
            make.left.right.equalToSuperview()
        }
    }
    
    
   
    //MARK: --------------------methods--------------------
    func bindAction() {
        bottomView.onClickShare = { [weak self] type in
            guard let self = self else {return}
            if type == 0 || type == 1 {
                // wx
                ZMShareManager.share(type: type == 0 ? .typeWechat : .subTypeWechatTimeline, images: [UIImage.init(named: "icon_512")!], title: "乐购惠生活", content: "\(ZMAppShareData.share.safeUserInfo.nickname)邀请您加入乐购惠生活", shareUrl: URL.init(string: CONFIG_INVITEURL)!) { state, userData, contentEntity, error in
                    switch state {
                        case .success:
                        ZMToast.showToast(title: "分享成功")
                        case .fail: ZMToast.showToast(title: "分享失败")
                        case .cancel: ZMToast.showToast(title: "分享取消")
                        default: break
                    }
                }
            } else if type == 2 {
                // copy
                UIPasteboard.general.string = CONFIG_INVITEURL
                ZMToast.showToast(title: "已复制")
            } else if type == 3 {
                // save
                let cells = self.collectionView.visibleCells
                if cells.count > 0 {
                    let afterSort = cells.sorted { one, two in
                        let cllectCenterOffsetX = self.collectionView.contentOffset.x + SCREEN_W / 2
                        let oneS = abs(cllectCenterOffsetX - one.center.x)
                        let twoS = abs(cllectCenterOffsetX - two.center.x)
                        return oneS < twoS
                    }
                    UIImageWriteToSavedPhotosAlbum(ZMOcHelper.image(withCaputureView: afterSort.first!), self, #selector(self.saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            }
        }
    }
    
    func fixScroll() {
        let size = collectionView.zm.size
        let width = 290 / 504 * size.height
        let contentOffset = collectionView.contentOffset
        let x = contentOffset.x
        let alength = width + 12
        let n = Int(x / alength)
        // 计算中心点差值
        let abv = x - CGFloat(n) * alength
        var r : CGFloat = 0
        if abv < alength / 2 {
            // 向下
            r = CGFloat(n) * alength
        } else {
            // 向上
            r = CGFloat(n + 1) * alength
        }
        collectionView.setContentOffset(CGPoint(x: r, y: 0), animated: true)
    }

    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            return
        }
        ZMToast.showToast(title: "保存成功")
    }
    
    func getPosters() {
        loading.showInView(fatherView: view)
        MineAPI.invitePoster.rxRequest(type: [String].self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.images = resp
            self.collectionView.reloadData()
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    //MARK: --------------------delegate--------------------
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        images.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InviteCell", for: indexPath) as! InviteCell
        cell.bgImg.zm.setImage(urlStr: images[indexPath.row])
        cell.code.zm.createCode(str: CONFIG_INVITEURL, centerImg: nil)
        cell.page.setTitle("\(indexPath.row + 1)/\(images.count)", for: .normal)
        cell.page.isHidden = true
        if let user = ZMAppShareData.share.userInfo.value {
            cell.name.setTitle(user.showId, for: .normal)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let size = collectionView.zm.size
        let width = 290 / 504 * size.height
        let offset = (SCREEN_W - width) / 2
        return UIEdgeInsets(top: 0, left: offset, bottom: 0, right: offset)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let size = collectionView.zm.size
//        290 / 504
        return CGSize(width: 290 / 504 * size.height, height: size.height)
    }
    
//    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//        print("end")
//    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        fixScroll()
    }
//
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//        fixScroll()
    }
    
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        scrollView.setContentOffset(scrollView.contentOffset, animated: false)
//        fixScroll()
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        fixScroll()
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print(scrollView.contentOffset)
    }
}
